﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using KTDSMS;

namespace KTD_XSMS
{
    public partial class Main : Form
    {
        XmlDocument Doc = new XmlDocument();
        private SerialPort port = new SerialPort();
        private KtdSms objclsSMS = new KtdSms();
        private ShortMessageCollection objShortMessageCollection = new ShortMessageCollection();
        public Main()
        {
            InitializeComponent();
        }
        #region Ham moi tao

        private PhoneTable[] SelectedRowsPhone()
        {
           
                int count = 0;
                for (int i = 0; i < this.phoneTable.Rows.Count - 1; i++)
                {
                    if ((bool)this.phoneTable.Rows[i].Cells["Select"].Value)
                    {
                        ++count;
                    }
                }
                PhoneTable[] phoneTables = new PhoneTable[count];
                count = 0;
                for (int i = 0; i < this.phoneTable.Rows.Count - 1; i++)
                {
                    if ((bool)this.phoneTable.Rows[i].Cells["Select"].Value)
                    {
                        phoneTables[count] = new PhoneTable();
                        phoneTables[count].Name = this.phoneTable.Rows[i].Cells["Name"].Value.ToString();
                        phoneTables[count].PhoneNo = this.phoneTable.Rows[i].Cells["PhoneNo"].Value.ToString();
                        count++;
                    }
                }
                return phoneTables;
        }


        public void Message(string mess)
        {
            MessageBox.Show(mess, "Thông báo hệ thống", MessageBoxButtons.OK);
        }

        private void LoadPhone(string id="0")
        {
            // Xoa sach du lieu trong luoi
            this.phoneTable.Columns.Clear();
            this.phoneTable.DataSource = (object)null;

            // Doc du lieu tu file XML ra datatable
            string filename = Application.StartupPath + "\\PhoneTable.xml";
            DataTable dataTablePhone = new DataTable();
            
            dataTablePhone = XMLManager.ReadToXML(filename);

            // Tao khung datatable cho luoi du lieu
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Select", typeof(bool));
            dataTable.Columns.Add("PhoneNo", typeof(string));
            dataTable.Columns.Add("Name", typeof(string));
            dataTable.Columns.Add("Status", typeof(string));


            if (dataTablePhone.Rows.Count > 0)
            {
                
                if (int.Parse(id) == 0)
                {
                    
                    for (int i = 0; i < dataTablePhone.Rows.Count; i++)
                    {
                        DataRow row = dataTable.NewRow();
                        row["Select"] = (object) false;
                        row["PhoneNo"] = (object) dataTablePhone.Rows[i]["PhoneNo"];
                        row["Name"] = (object) dataTablePhone.Rows[i]["Name"];
                        row["Status"] = "";
                        dataTable.Rows.Add(row);
                    }
                }
                else
                {
                    
                    for (int i = 0; i < dataTablePhone.Rows.Count; i++)
                    {
                        DataRow row = dataTable.NewRow();
                        if (id == dataTablePhone.Rows[i]["ID"].ToString())
                        {
                            row["Select"] = (object) false;
                            row["PhoneNo"] = (object) dataTablePhone.Rows[i]["PhoneNo"];
                            row["Name"] = (object) dataTablePhone.Rows[i]["Name"];
                            row["Status"] = "";
                            dataTable.Rows.Add(row);
                        }
                    }
                }
            }
            else
            {
                Message("No Data");
            }


            this.phoneTable.DataSource = (object)dataTable;
            lblTongSo.Text = dataTablePhone.Rows.Count.ToString();
            
        }


        private void LoadGroupCustomer()
        {
            // Doc du lieu tu file XML ra datatable
            string filename = Application.StartupPath + "\\Group.xml";
            DataTable dataTableGroup = new DataTable();

            dataTableGroup = XMLManager.ReadToXML(filename);
            if (dataTableGroup.Rows.Count > 0)
            {
                ComboboxItem item = new ComboboxItem();
                for (int i = 0; i < dataTableGroup.Rows.Count; i++)
                {
                    item.Text = dataTableGroup.Rows[i]["GroupName"].ToString();
                    item.Value = dataTableGroup.Rows[i]["ID"].ToString();
                    cboGroup.Items.Add(item);
                }
                
            }
            else
            {
                Message("No Data");
            }
        }

        #endregion
        private void Main_Load(object sender, EventArgs e)
        {
            LoadPhone();
            LoadGroupCustomer();
           
            try
            {
                foreach (object obj in SerialPort.GetPortNames())
                    this.cboPortName.Items.Add(obj);
            }
            catch (Exception ex)
            {
                this.ErrorLog(ex.ToString());
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            PhoneTable[] phoneTables = this.SelectedRowsPhone();

            if (phoneTables.Count() <= 0)
            {
                Message("Hãy chọn số muốn sửa");
            }
            else if (phoneTables.Count() > 1)
            {
                Message("Chỉ chọn 1 số để sửa");
            }
            else
            {
                int num2 = (int)new EditPhone()
                {
                    phoneNo = phoneTables[0].PhoneNo,
                    name = phoneTables[0].Name
                }.ShowDialog();
                this.LoadPhone();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
         

            ComboboxItem item = new ComboboxItem();
            item = (ComboboxItem) cboGroup.SelectedItem;

            new AddPhone()
                {
                    id = item.Value
                }.ShowDialog();
            this.LoadPhone();
        }

        private void btnDell_Click(object sender, EventArgs e)
        {
            PhoneTable[] phoneTables = this.SelectedRowsPhone();

            if (phoneTables.Count() <= 0)
            {
                Message("Select phone number.");
            }
            else if (MessageBox.Show("You want delete " + phoneTables.Count().ToString() + " phone number selected?", "Thông báo hệ thống",
                                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DelPhone(phoneTables);
                this.LoadPhone();
            }
        }
        private void DelPhone(PhoneTable[] phoneTables)
        {
            Doc.Load(Application.StartupPath + "\\PhoneTable.xml");
            XmlNode node;
            foreach (PhoneTable phoneTable in phoneTables)
            {
                node = Doc.SelectSingleNode("/PhoneTables/PhoneTable[PhoneNo='" + phoneTable.PhoneNo + "']");
                if (node != null)
                {
                    Doc.DocumentElement.RemoveChild(node);
                }
            }
            Message("Delete success " + phoneTables.Count().ToString() + " phone number.");
            Doc.Save(Application.StartupPath + "\\PhoneTable.xml");
        }

        private void buttonImportPhone_Click(object sender, EventArgs e)
        {
            importDatabases();
        }

        private void importDatabases()
        {
            DataTable dataTable1 = new DataTable();          
            bool flag = false;
           // this.importFile.Filter = "Excel 2007-2013 (.xlsx)|*.xlsx";
           // this.importFile.FilterIndex = 1;
           // this.importFile.Multiselect = false;

  //       if (this.importFile.ShowDialog() == DialogResult.OK)
          //  {
                string FileNameExel = System.IO.Directory.GetCurrentDirectory().ToString() + @"\ImportFile.xlsx";
                OleDbConnection connection = (OleDbConnection)null;
                try
                {
                    connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileNameExel + ";Extended Properties=Excel 12.0;Persist Security Info=False");
                    OleDbCommand selectCommand = new OleDbCommand("Select [PhoneNo],[Name] FROM [Sheet1$]", connection);
                    connection.Open();
                    ((DbDataAdapter)new OleDbDataAdapter(selectCommand)).Fill(dataTable1);
                    flag = true;
                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (connection.State == ConnectionState.Open)
                        connection.Close();
                    flag = false;
                    Unity.Message("Cannot import data from file. Please check your file. Error: " + ex.Message);
                    Unity.Message("*) Lưu ý khi ImportFile: \r - File phải đặt tên là ImportFile.xlsx đặt tại thư mục cài chương trình \r - Dữ liệu đặt tại sheet1 và có tiêu đề 2 trường là PhoneNo và Name");
                }
          //  }
            if (!flag)
                return;
            
            for (int i = 0; i < dataTable1.Rows.Count; i++)
            {
                SavePhone(dataTable1.Rows[i]["PhoneNo"].ToString(), dataTable1.Rows[i]["Name"].ToString());
            }

            this.LoadPhone();
            Unity.Message("Import Success");
        }

        private void SavePhone(string phoneNumber, string nameContact)
        {
            Doc.Load(Application.StartupPath + "\\PhoneTable.xml");
            XmlElement Phone_Table, Ten, SoDT;
            Phone_Table = Doc.CreateElement("PhoneTable");
            Ten = Doc.CreateElement("Name");
            SoDT = Doc.CreateElement("PhoneNo");

            Ten.InnerText = nameContact;
            SoDT.InnerText = phoneNumber;

            Phone_Table.AppendChild(Ten);
            Phone_Table.AppendChild(SoDT);

            Doc.DocumentElement.AppendChild(Phone_Table);
            Doc.Save(Application.StartupPath + "\\PhoneTable.xml");

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.cboPortName.Text))
            {
                int num = (int)MessageBox.Show("Please select COM port");
            }
            else
            {
                try
                {
                    this.port = this.objclsSMS.OpenPort(this.cboPortName.Text, Convert.ToInt32(this.cboBaudRate.Text), Convert.ToInt32(this.cboDataBits.Text), 300, 300);
                    if (this.port != null)
                    {
                        this.gboPortSettings.Enabled = false;
                        this.statusBar1.Text = "Modem is connected at PORT " + this.cboPortName.Text;
                      
                        this.lblConnectionStatus.Text = "Connected at " + this.cboPortName.Text;
                        this.btnDisconnect.Enabled = true;
                        this.btnSendSMS.Enabled = true;

                    }
                    else
                        this.statusBar1.Text = "Invalid port settings";
                }
                catch (Exception ex)
                {
                    this.ErrorLog(ex.Message);
                    this.statusBar1.Text = "Connect Fail";
                }
            }
        }

        public void ErrorLog(string Message)
        {
            StreamWriter streamWriter = (StreamWriter)null;
            try
            {
                DateTime now = DateTime.Now;
                string str1 = ((object)now.ToShortDateString()).ToString();
                string str2 = " ";
                now = DateTime.Now;
                string str3 = ((object)now.ToLongTimeString()).ToString();
                string str4 = " ==> ";
                string str5 = str1 + str2 + str3 + str4;
                string str6 = "SMSapplicationErrorLog_";
                now = DateTime.Now;
                string str7 = now.Year.ToString();
                now = DateTime.Now;
                string str8 = now.Month.ToString();
                now = DateTime.Now;
                string str9 = now.Day.ToString() + "-" + str8 + "-" + str7;
                streamWriter = new StreamWriter(str6 + str9 + ".txt", true);
                streamWriter.WriteLine(str5 + Message);
                ((TextWriter)streamWriter).Flush();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Dispose();
                    streamWriter.Close();
                }
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                this.gboPortSettings.Enabled = true;
                this.objclsSMS.ClosePort(this.port);
                this.lblConnectionStatus.Text = "Not Connected";
                this.btnDisconnect.Enabled = false;
                this.btnSendSMS.Enabled = false;
            }
            catch (Exception ex)
            {
                this.ErrorLog(ex.Message);
            }
        }

        private void ClearColummStatus()
        {
            for (int i = 0; i < this.phoneTable.Rows.Count - 1; i++)
            {
                this.phoneTable.Rows[i].Cells["Status"].Value = "";
            }
        }
        private void btnSendSMS_Click(object sender, EventArgs e)
        {
            ClearColummStatus();
            string str = (string)null;
            int num1 = 0;
            int num2 = 0;

            PhoneTable[] phoneTables = this.SelectedRowsPhone();
            if (phoneTables.Count() < 1)
            {
                Message("Please select phone number");
                return;
            }

            if (txtMessage.Text == "")
            {
                Message("Please input message");
                txtMessage.Focus();
                return;
            }

            for (int i = 0; i < this.phoneTable.Rows.Count-1; i++)
            {
                num1++;//So tin da gui
                bool giatri = (bool) this.phoneTable.Rows[i].Cells["Select"].Value;

                if (giatri) // neu dong duoc chon (checked) thì tiến hành gửi tin nhắn
                {
                    // Ghi vào trạng thái là đang gửi
                    this.phoneTable.Rows[i].Cells["Status"].Value = "Sending...";
                    this.phoneTable.Refresh();
                    string phoneNo = this.phoneTable.Rows[i].Cells["PhoneNo"].Value.ToString();
                    string mess = this.txtMessage.Text;
                    
                    try
                    {
                        bool test = this.objclsSMS.sendMsg(this.port, phoneNo, mess);    
                        if (test)
                        {
                            num2++;//so tin gui thanh cong
                            this.phoneTable.Rows[i].Cells["Status"].Value= "Success"; //Gui thanh cong
                            this.phoneTable.Refresh();
                        }
                        else
                        {
                            this.phoneTable.Rows[i].Cells["Status"].Value = "Fail"; // Gui that bai
                            this.phoneTable.Refresh();
                        }
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(16000);
                        this.phoneTable.Rows[i].Cells["Status"].Value = ex.Message; // Gui that bai
                        this.phoneTable.Refresh();
                       // this.ErrorLog(ex.Message);
                    }
                }
               

            }
        }

        private void btnChangePass_Click(object sender, EventArgs e)
        {
            new ChangePass().ShowDialog();
        }

        private void phoneTable_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5) 
            {
                ClearColummStatus();

            }


        }

        private void ckbSelect_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbSelect.Checked)
            {
                for (int i = 0; i < this.phoneTable.Rows.Count - 1; i++)
                {

                    this.phoneTable.Rows[i].Cells["Select"].Value = true;
                }
            }
            else
            {
                for (int i = 0; i < this.phoneTable.Rows.Count - 1; i++)
                {

                    this.phoneTable.Rows[i].Cells["Select"].Value = false;
                }
            }
        }

        private void phoneTable_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string s = cboNetwork.SelectedItem.ToString();
            for (int i = 0; i < this.phoneTable.Rows.Count - 1; i++)
            {
                this.phoneTable.Rows[i].Cells["Select"].Value = false;
                if (s == Unity.Incontent(this.phoneTable.Rows[i].Cells["PhoneNo"].Value.ToString()))
                {
                    this.phoneTable.Rows[i].Cells["Select"].Value = true;
                }
            }
        }

        private void cboGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboboxItem item = new ComboboxItem();
            item = (ComboboxItem) cboGroup.SelectedItem;
            MessageBox.Show(item.Value);
            LoadPhone(item.Value);
        }

       
       

       

    }
}
